﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using NBlock.MVCExtensions;
using NBlock.Core;
using Cost.Services;

namespace Cost.Controllers
{
    public class RoleController : Controller
    {
        #region 构造函数
        private readonly ICostRepository<Role> roleRepository;
        private readonly ICostRepository<UserInfo> userRepository;
        private readonly ICostRepository<UserRole> userRoleRepository;
        private readonly ICostRepository<UserRoleRelation> userRoleRelationRepository;
        private readonly ICostRepository<Permission> permissionRepository;
        private readonly ICostRepository<Privilege> privilegeRepository;
        private readonly PrivilegeService privilegeService;

        public RoleController(ICostRepository<Role> roleRepository,
            ICostRepository<UserRoleRelation> userRoleRelationRepository,
            ICostRepository<UserRole> userRoleRepository,
            ICostRepository<UserInfo> userRepository,
            ICostRepository<Permission> permissionRepository,
            ICostRepository<Privilege> privilegeRepository,
            PrivilegeService privilegeService)
        {
            this.roleRepository = roleRepository;
            this.userRoleRelationRepository = userRoleRelationRepository;
            this.userRoleRepository = userRoleRepository;
            this.userRepository = userRepository;
            this.permissionRepository = permissionRepository;
            this.privilegeRepository = privilegeRepository;
            this.privilegeService = privilegeService;
        }
        #endregion

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Edit(string Id)
        {
            var data = roleRepository.Find(Id) ?? new Role();
            data.SeqNo = data.SeqNo ?? 9999;
            return View(data);
        }

        public JsonResult Save(string Id)
        {
            var data = roleRepository.Find(Id) ?? new Role();
            TryUpdateModel(data);
            roleRepository.Save(data);
            return Json(nbAjaxMessage.Successful);
        }

        public JsonResult Delete(string Id)
        {
            roleRepository.Delete(Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteAll(string Ids)
        {
            var items = Ids.Split(',');
            roleRepository.DeleteAll(d => items.Contains(d.Id));
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult List(nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = roleRepository.GetPageable(pager, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        [HttpPost]
        public JsonResult GetRoleCode(string name)
        {
            var code = string.Empty;
            if (!string.IsNullOrWhiteSpace(name))
            {
                code = HZ2PY.GetFirstPY(name);
            }
            return Json(nbAjaxMessage.Successful.SetData(code));
        }

        #region 角色用户
        public ActionResult RoleUser(string roleId)
        {
            ViewBag.RoleId = roleId;
            return View();
        }

        [HttpPost]
        public JsonResult RoleUser(string roleId, nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = userRoleRelationRepository.GetPageable(pager, u => u.RoleId == roleId, where);
            return Json(pager.ToGridData(pageData));
        }

        public ActionResult SetRoleUser(string roleId)
        {
            ViewBag.RoleId = roleId;
            return View();
        }

        [HttpPost]
        public JsonResult AddRoleUser(string roleId, string userids)
        {
            var role = roleRepository.Find(roleId);
            if (role != null)
            {
                // 查出所有选中用户
                var ids = userids.Split(',');
                var userlist = userRepository.FindAll(u => ids.Contains(u.Id));

                // 插入数据
                foreach (var user in userlist)
                {
                    userRoleRepository.Insert(new UserRole
                    {
                        Id = Guid.NewGuid().ToString(),
                        RoleId = role.Id,
                        RoleCode = role.RoleCode,
                        UserId = user.Id,
                        UserCode = user.UserCode,
                    });
                }
            }

            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult RemoveRoleUser(string Id)
        {
            userRoleRepository.Delete(Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult RemoveRoleUsers(string Ids)
        {
            var items = Ids.Split(',');
            userRoleRepository.DeleteAll(u => items.Contains(u.Id));
            return Json(nbAjaxMessage.Successful);
        }
        #endregion

        #region 角色权限（授权）
        public ActionResult RolePrivilege(string roleId)
        {
            ViewBag.RoleId = roleId;
            return View();
        }

        [HttpPost]
        public JsonResult SetRolePrivilege(string roleId, string ids)
        {
            // 查找角色
            var role = roleRepository.Find(roleId);
            if (role != null)
            {
                // 先清空指定角色的所有权限
                permissionRepository.DeleteAll(p => p.MasterValue == roleId && p.MasterType == "Role");

                // 插入添加的所有权限
                var items = ids.Split(',');
                foreach (var p in privilegeRepository.FindAll(r => items.Contains(r.Id)))
                {
                    permissionRepository.Insert(new Permission
                    {
                        Id = Guid.NewGuid().ToString(),
                        MasterValue = role.Id,
                        MasterType = "Role",
                        PrivilegeId = p.Id,
                        PrivilegeCode = p.PrivilegeCode,
                        PrivilegeType = p.PrivilegeType,
                        Operation = "Permit",
                    });
                }
            }
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult GetRolePrivileges(string roleId, string Id)
        {
            var permissions = permissionRepository.FindAll(p => p.MasterValue == roleId && p.MasterType == "Role").ToList();
            var privileges = privilegeService.GetPrivilegesByParentId(Id);
            var treeData = CommonLogic.GetSubPrivilegeTree(Id, privileges, permissions);
            return Json(treeData);
        }
        #endregion
    }
}
